package com.zl.codereview;


import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.vcs.annotate.AnnotationProvider;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBScrollPane;
import com.zl.codereview.git.GitService;
import com.zl.codereview.git.model.ProjectFileCode;
import com.zl.codereview.review.ReviewChat;
import com.zl.codereview.review.ReviewContent;
import com.zl.codereview.util.DateUtils;
import com.zl.codereview.util.IdeaUtils;
import com.zl.codereview.util.ObjectUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.zl.codereview.review.ReviewConstant.REVIEW_DIR_PATH;

public class ReviewDialog extends JDialog implements ActionListener, MouseListener {

    private JButton confirm,cancel;
    private Project project;
    private AnActionEvent e;
    private ReviewContent reviewContent;
    private GitService gitService = new GitService();
    private int lineNum;
    private String branchName;
    private String modulePath;
    private String username;
    private String codeReviewPath;
    private String filePath;
    private String fileName;
    private List<ReviewContent> reviewContents;
    private ComboBox<String> comboBox;


    /**
     * 操作 1 查看 2 添加 3 修改 4 处理
     */
    private int operate;

    /**
     * 初始化git相关信息
     */
    private void initBaseMsg(){
        //项目
        this.project = e.getProject();
        //模块路径
        this.modulePath = IdeaUtils.getModuleFilePath(e);
        //当前git用户
        this.username = gitService.getUser(this.modulePath);
        //当前文件路径
        VirtualFile file = e.getData(CommonDataKeys.VIRTUAL_FILE);
        if(!ObjectUtils.isEmpty(file)){
            this.filePath = file.getPath();
            this.fileName = file.getName();
        }
        //模块分支名称
        this.branchName = gitService.branchName(modulePath);
        if (this.branchName.contains("/")) {
            this.branchName = this.branchName.replaceAll("/","-");
        }
        //代码评审路径
        this.codeReviewPath = modulePath + REVIEW_DIR_PATH + "/" + branchName+".ser";
        //当前点击所在行号
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        if (project != null && editor != null) {
            // 获取光标所在行号
            this.lineNum = editor.getCaretModel().getLogicalPosition().line + 1; // 行号从1开始计数
        }
        //初始化代码评审内容，如果当前文件当前行数有，则赋值
        this.reviewContents  = IdeaUtils.parseObject(codeReviewPath);
        if(!ObjectUtils.isEmpty(reviewContents)){
            this.reviewContent = reviewContents.stream().filter(r -> r.getPath().equals(filePath) && r.getNumber() == lineNum)
                    .findFirst().orElse(null);
        }else{
            this.reviewContents = new ArrayList<>();
        }
        if(ObjectUtils.isEmpty(reviewContent)){
            this.reviewContent = new ReviewContent();
            this.reviewContent.setReviewId(IdeaUtils.uuid());
            this.reviewContent.setCreateTime(new Date());
            this.reviewContent.setAuthor(username);
            this.reviewContent.setFileName(fileName);
            this.reviewContent.setNumber(lineNum);
            this.reviewContent.setPath(filePath);
            this.reviewContent.setStatus(1);
            this.reviewContent.setChats(new ArrayList<>());
            this.reviewContents.add(this.reviewContent);
        }
    }

    private ComboBox<String> initComboBox(){
        // 创建一个 ComboBox 的模型
        DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();

        // 添加选项
        List<String> authors = gitService.getAuthors(modulePath);
        for(String author : authors){
            model.addElement(author);
        }
        // 创建 ComboBox 组件
        ComboBox<String> comboBox = new ComboBox<>(model);

        // 设置选择事件监听器
        comboBox.addActionListener(e -> {
            String author = (String) comboBox.getSelectedItem();
            this.reviewContent.setCodeAuthor(author);
        });
        if(!ObjectUtils.isEmpty(this.reviewContent.getCodeAuthor())){
            comboBox.setSelectedItem(this.reviewContent.getCodeAuthor());
        }
        return comboBox;
    }

    public ReviewDialog(AnActionEvent e,int operate){
        this.e = e;
        this.operate = operate;
        //初始化基础信息
        initBaseMsg();
        setModal(true);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        int width = 600;
        int height = 290;
        setSize(width, height);
        setLayout(null);
        setTitle("code review");
        this.setLocationRelativeTo(null);


        // 创建表单组件
        JLabel label1 = new JLabel("评价人:  ",SwingConstants.RIGHT);
        label1.setBounds(10,10,60,30);
        JLabel label11 = new JLabel(this.reviewContent.getAuthor());
        label11.setBounds(80,10,100,30);
        this.add(label1);
        this.add(label11);

        if(this.reviewContent.getStatus() == 2) {
            JLabel labelJiejue = new JLabel("已解决");
            labelJiejue.setForeground(JBColor.GREEN);
            labelJiejue.setBounds(200, 10, 200, 35);
            this.add(labelJiejue);
        }

        String time = DateUtils.dateToStrLong(this.reviewContent.getCreateTime() == null ? new Date() : this.reviewContent.getCreateTime());
        JLabel label2 = new JLabel("评价时间:  ",SwingConstants.RIGHT);
        label2.setBounds(10,50,60,30);
        JLabel label22 = new JLabel(time);
        label22.setBounds(80,50,150,30);
        this.add(label2);
        this.add(label22);

        //指派人
        JLabel zhipaiLabel = new JLabel("指派人:  ",SwingConstants.RIGHT);
        zhipaiLabel.setBounds(10,90,60,30);
        ComboBox<String> comboBox = initComboBox();
        comboBox.setBounds(80,90,100,30);

        JLabel label = new JLabel("评价内容:  ",SwingConstants.RIGHT);
        label.setBounds(10,130,60,30);
        JTextArea contentArea = new JTextArea(5,15);
        contentArea.setBounds(80,140,460,150);
        contentArea.setText(reviewContent.getContent());
        contentArea.setName("reviewContent");
        contentArea.setLineWrap(true);
        contentArea.setWrapStyleWord(true);
        if(this.operate == 1){
            //查看下不可编辑
            contentArea.setEditable(false);
        }
        contentArea.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
            }
            @Override
            public void focusLost(FocusEvent e) {
                String text = contentArea.getText();
                reviewContent.setContent(text);
            }
        });
        JBScrollPane contentScrollPane = new JBScrollPane(contentArea,
                JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JBScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        contentScrollPane.setBounds(80,140,460,150);

        int y = 300;

        if(operate == 1 || operate == 4){
            JLabel label3 = new JLabel("解决人:  ",SwingConstants.RIGHT);
            label3.setBounds(10,300,60,30);

            JLabel label33 = new JLabel();
            label33.setBounds(80,300,150,30);

            JLabel label4 = new JLabel("解决内容:  ",SwingConstants.RIGHT);
            label4.setBounds(10,340,60,50);
            JTextArea handArea = new JTextArea(5,15);
            handArea.setBounds(80,345,460,60);
            handArea.setName("handleContent");
            handArea.setLineWrap(true);
            handArea.setWrapStyleWord(true);
            JBScrollPane handScrollPane = new JBScrollPane(handArea,
                    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            handScrollPane.setBounds(80,345,460,100);
            if(operate == 1){
                handArea.setEditable(false);
            }
            if(operate == 1 && !ObjectUtils.isEmpty(reviewContent.getChats())){
                ReviewChat reviewChat = reviewContent.getChats().get(0);
                label33.setText(reviewChat.getAuthor());
                handArea.setText(reviewChat.getMsg());
            }else if(operate == 4){
                label33.setText(username);
                handArea.addFocusListener(new FocusListener() {
                    @Override
                    public void focusGained(FocusEvent e) {
                    }
                    @Override
                    public void focusLost(FocusEvent e) {
                        String text = handArea.getText();
                        ReviewChat chat = new ReviewChat();
                        chat.setAuthor(username);
                        chat.setCreateTime(new Date());
                        chat.setMsg(text);
                        reviewContent.setChats(Collections.singletonList(chat));
                    }
                });
            }
            y = 450;
            this.add(label3);
            this.add(label33);
            this.add(label4);
            this.add(handScrollPane);
        }

        this.add(label1);
        this.add(label2);
        this.add(zhipaiLabel);
        this.add(comboBox);
        this.add(label);
        this.add(contentScrollPane);

        confirm = new JButton("确定");
        confirm.setBounds(500,y,60,25);
        confirm.addActionListener(this);

        cancel = new JButton("取消");
        cancel.setBounds(420,y,60,25);
        cancel.addActionListener(this);

        this.add(cancel);
        this.add(confirm);
        setSize(width, y+80);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == this.cancel){
            this.dispose();
        }else if(e.getSource() == this.confirm){
            if(operate == 4) {
                reviewContent.setHandler(username);
                reviewContent.setHandleTime(new Date());
                reviewContent.setStatus(2);
            }
            if(operate == 3){
                this.reviewContent.setStatus(1);
            }
            IdeaUtils.createDir(modulePath + REVIEW_DIR_PATH);
            IdeaUtils.writeObject(this.reviewContents,codeReviewPath);
            if(reviewContent.getStatus() == 2) {
                IdeaUtils.addGutterIcon(project,this.reviewContent.getAuthor()+": "+this.reviewContent.getContent(), this.reviewContent.getNumber(), 2);
            }else if(reviewContent.getStatus() == 1){
                IdeaUtils.addGutterIcon(project,this.reviewContent.getAuthor()+": "+this.reviewContent.getContent(), this.reviewContent.getNumber(),1);
            }
            ReviewView reviewView = ReviewSidebarFrame.getReviewView();
            if(!ObjectUtils.isEmpty(reviewView)){
                reviewView.refresh();
            }
            this.dispose();
        }
    }


    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
